﻿namespace YdmCodeArtCoreApplication.Tests
{
    using System.Reflection;
    using Abp.EntityFrameworkCore.Configuration;
    using Abp.Modules;
    using Abp.Reflection.Extensions;
    using Abp.TestBase;
    using Castle.MicroKernel.Registration;
    using Castle.Windsor.MsDependencyInjection;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using FFF.Test.Application.Framework;
    using FFF.Test.DataAccess.Framework;
    using FFF.Test.DataAccess.Framework.Configuration;
    using FFF.Test.Util;
    using FFF.Test.Util.Denpends;

    /// <summary>
    /// test
    /// </summary>
    [DependsOn(
        typeof(YudmAbpApplicationModule),
        typeof(AbpTestBaseModule))]
    public class YdmCodeArtCoreApplicationTestModule : AbpModule
    {
        public override void PreInitialize()
        {
            base.IocManager.Register<IConfiguration, MyConfigForDenpends>();
            this.Configuration.UnitOfWork.IsTransactional = false;
            this.SetupInMemoryDb();
        }

        public override void Initialize()
        {
            base.IocManager.RegisterAssemblyByConvention(typeof(YdmCodeArtCoreApplicationTestModule).GetAssembly());
        }

        private void SetupInMemoryDb()
        {
            var services = new ServiceCollection()
                .AddEntityFrameworkInMemoryDatabase();

            var serviceProvider = WindsorRegistrationHelper.CreateServiceProvider(
                base.IocManager.IocContainer,
                services
            );

            var builder = new DbContextOptionsBuilder<MyDbContext>();
            builder.UseInMemoryDatabase().UseInternalServiceProvider(serviceProvider);

            base.IocManager.IocContainer.Register(
                Component
                    .For<DbContextOptions<MyDbContext>>()
                    .Instance(builder.Options)
                    .LifestyleSingleton()
            );
        }
    }
}